package com.tianji.aigc.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.tianji.aigc.agent.AbstractAgent;
import com.tianji.aigc.agent.Agent;
import com.tianji.aigc.enums.AgentTypeEnum;
import com.tianji.aigc.enums.ChatEventTypeEnum;
import com.tianji.aigc.service.ChatService;
import com.tianji.aigc.vo.ChatEventVO;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import reactor.core.publisher.Flux;

import java.util.Map;
import java.util.Objects;

//@Service
//@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "tj.ai", name = "chat-type", havingValue = "ROUTE")
public class AgentServiceImpl implements ChatService {

//    private final ChatClient openAiChatClient;
    @Override
    public Flux<ChatEventVO> chat(String question, String sessionId) {
//        先把问题发给意图分析智能体, 在决定由哪个智能体执行
        var result = Objects.requireNonNull(this.finAgentByType(AgentTypeEnum.ROUTE)).process(question, sessionId);

//        通过结果, 尝试查找智能体实例, 如果能找到, 就进行执行, 找不到, 就说明路由智能体可以处理的问题, 直接返回结果
        Agent agent = this.finAgentByType(AgentTypeEnum.agentNameOf(result));
        if (null == agent) {
            ChatEventVO chatEventVO = ChatEventVO.builder()
                    .eventType(ChatEventTypeEnum.DATA.getValue())
                    .eventData(result)
                    .build();
            return Flux.just(chatEventVO, AbstractAgent.STOP_EVENT);
        }

//        交由下游的智能体执行
        return agent.processStream(question, sessionId);
    }

    private Agent finAgentByType(AgentTypeEnum agentTypeEnum) {
        if (null == agentTypeEnum) {
            return null;
        }

//        从spring容器中读取所有的实例, 再通过type进行筛选
        Map<String, Agent> beans = SpringUtil.getBeansOfType(Agent.class);
        for (Agent agent : beans.values()) {
            if (agent.getAgentType() == agentTypeEnum) {
                return agent;
            }
        }

        return null;
    }


    @Override
    public void stop(String sessionId) {
        Objects.requireNonNull(this.finAgentByType(AgentTypeEnum.ROUTE)).stop(sessionId);
    }


    @Override
    public String chatText(String question) {
        return /*this.openAiChatClient.prompt()
                .system(promptSystem -> promptSystem.text(this.systemPromptConfig.getTextSystemMessage().get()))
                .user(question)
                .call()
                .content()*/null;
    }
}
